<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Thu, 1 Jan 1970 01:00:00 GMT"); // Date in the past
header('Content-type: application/json');
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
ini_set('log_errors', '1');
ini_set('error_log', 'php_error.log');
ini_set('display_errors', '1');

chdir("../");
include_once("file.common.php");

$skipChecks = FALSE;

$spaceName = req('spaceName', '');
$curatePassword = req('curatePassword', '');
$curateEmail = req('curateEmail', '');
$createTime = req('createTime', time() * 1000);
$update = req('update', FALSE);

if ($update !== FALSE)
{
	authenticate($validCredentials);
	$skipChecks = TRUE;
}

$result = TRUE;
$srcDir = "../../creator";
$dstDir = "../../spaces/$spaceName";
$exclude = array("pg", "db", "md", "ph", "sc", "bk", "pages", "spaces", "curator.php", "PlaySpace.css");
$msg = '';
$log = array();
$totalDirs = 0;
$totalFiles = 0;
$totalSize = 0;
$activateId = substr("A" . md5(mt_rand(100000, 100000000)), 0, 32);

function UserID($email) {
	$uu = explode('.', uniqid('', true));
	return substr("U" . dechex(mt_rand()) . $uu[0] . dechex($uu[1]) . sha1($email), 0, 32);
}

/** 
 * Recursively delete a directory 
 * 
 * @param string $dir Directory name 
 * @param boolean $deleteRootToo Delete specified top-level directory as well 
 */ 
function RoboDelete($dir, $deleteRootToo) 
{ 
    if(!$dh = @opendir($dir)) 
    { 
        return false;
    } 
    while (false !== ($obj = readdir($dh))) 
    { 
        if($obj == '.' || $obj == '..') 
        { 
            continue; 
        } 

        if (!@unlink($dir . '/' . $obj)) 
        { 
            unlinkRecursive($dir.'/'.$obj, true); 
        } 
    } 

    closedir($dh); 
    
    if ($deleteRootToo) 
    { 
        return @rmdir($dir); 
    } 
    
    return true; 
} 

/** 
 * Recursively duplicate a file or directory with file and folder exclusions
 */ 
function RoboCopy( $source, $destination, $exclude ) {
	global $log, $totalFiles, $totalDirs, $totalSize;
	if (!$exclude)
		$exclude = array();
	if ( is_dir( $source ) ) {
		$pinfo = pathinfo($source);
		if (in_array($pinfo['basename'], $exclude))
		{
			$log["exclude: $source"] = $pinfo['basename'];
			return;
		}
		//@mkdir( $destination); // use this one for logging only, no creates
		@mkdir( $destination, 0777, true );
		$log["mkdir: $source"] = "$destination";
		$totalDirs += 1;
		$directory = dir( $source );
		while ( FALSE !== ( $item = $directory->read() ) ) {
			if ( $item == '.' || $item == '..' ) {
				continue;
			}
			$PathDir = $source . '/' . $item; 
			if ( is_dir( $PathDir ) ) {
				RoboCopy( $PathDir, $destination . '/' . $item, $exclude );
				continue;
			}
			$pinfo = pathinfo($PathDir);
			if (in_array($pinfo['basename'], $exclude))
			{
				$log["exclude: $PathDir"] = "$destination/$item";
				continue;
			}
			@copy( $PathDir, $destination . '/' . $item );
			$log["copy: $PathDir"] = "$destination/$item";
			$totalSize += filesize("$destination/$item");
			$totalFiles += 1;
		}
 
		$directory->close();
	} else {
		$pinfo = pathinfo($source);
		if (in_array($pinfo['basename'], $exclude))
		{
			$log["exclude: $source"] = $pinfo['basename'];
			return;
		}
		@copy( $source, $destination );
		$log["copy: $source"] = "$destination";
		$totalSize += filesize("$destination");
		$totalFiles += 1;
	}
}

if ($skipChecks === TRUE || !file_exists($dstDir))
{
	// Copy the software
	RoboCopy($srcDir, $dstDir, $exclude);
	
	// Remove destination .src.css files
	foreach (glob("$dstDir/$appPath/cs/*.src.css") as $filename) {
		@unlink($filename);
	}
	
	if (!$devserver)
	{
		// Remove Scripts .debug.js files
		foreach (glob("$dstDir/Scripts/Scripts/*.debug.js") as $filename) {
			@unlink($filename);
		}
		foreach (glob("$dstDir/$appPath/sc/*.debug.js") as $filename) {
			@unlink($filename);
		}
	}
	
	// Copy the source admin page to the new admin page
	RoboDelete("$dstDir/$appPath/pg/gigs/admin");
	RoboCopy("$srcDir/$appPath/pg/gigs/admin", "$dstDir/$appPath/pg/gigs/admin", array());
	
	// Copy the default Theme to the new space
	// The source here can be changed to generate differently themed spaces
	@mkdir("$dstDir/$appPath/sc", 0777, true);
	RoboCopy("$srcDir/Scripts/Scripts/Theme.js", "$dstDir/$appPath/sc/Theme.js", array());

	// Copy the source homestub to the new published home page if it doesn't exist
	if (!file_exists("$dstDir/pages/home.html"))
	{
		@mkdir("$dstDir/pages", 0777, true);
		RoboCopy("$srcDir/Scripts/Data/homestub.html", "$dstDir/pages/home.html", array());
	}

	if ($update !== TRUE)
	{
		// Create the $usercode
		$usercode = UserID($curateEmail);

		// Copy the source home page to the new home page
		RoboCopy("$srcDir/$appPath/pg/gigs/newhome", "$dstDir/$appPath/pg/gigs/home", array());
		
		// Copy the indexnew.html page to index.html
		RoboCopy("$srcDir/Scripts/Data/indexnew.html", "$dstDir/index.html", array());
		
		// Copy a default Pages.txt file
		RoboCopy("$srcDir/$appPath/pg/gigs/Pages.tpl.txt", "$dstDir/$appPath/pg/gigs/Pages.txt", array());

		// Create the passcode file
		$credfile = "<?PHP\n";
		$credfile .= '$newPasscode = ' . json_encode(md5($curatePassword)) . ";\n";
		$credfile .= '$srcPasscode = ' . json_encode($curatePassword) . ";\n";
		$credfile .= '$curateEmail = ' . json_encode($curateEmail) . ";\n";
		$credfile .= '$usercode = ' . json_encode($usercode) . ";\n";
		$credfile .= '$createTime = ' . json_encode($createTime) . ";\n";
		$credfile .= '$notactiveId = ' . json_encode($activateId) . ";\n";
		$credfile .= "?>\n";
		file_put_contents("$dstDir/$appPath/curator.php", $credfile);
	}
}
else
{
	$msg = "Space already exists";
}

if ($callback)
	$ee .= "$callback({\n";
else
	$ee .= "{\n";
$ee .= '"result":' . json_encode($result) . ",\n";
$ee .= '"userid":' . json_encode($usercode) . ",\n";
$ee .= '"update":' . json_encode($update) . ",\n";
$ee .= '"srcDir":' . json_encode($srcDir) . ",\n";
$ee .= '"dstDir":' . json_encode($dstDir) . ",\n";
$ee .= '"totalDirs":' . json_encode($totalDirs) . ",\n";
$ee .= '"totalFiles":' . json_encode($totalFiles) . ",\n";
$ee .= '"totalSize":' . json_encode($totalSize) . ",\n";
$ee .= '"activateId":' . json_encode($activateId) . ",\n";
$ee .= '"msg":' . json_encode($msg) . ",\n";
$ee .= '"log":' . json_encode($log) . ",\n";
$ee .= '"end":true' . "\n";
if ($callback)
	$ee .= "})";
else
	$ee .= "}";
echo $ee;

?>